﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;
using UnityEngine;

public class DynamicSaveManager : MonoBehaviour
{
    public static DynamicSaveManager Instance;

    private void Awake()
    {
        Instance = this;
    }

    [SerializeField] public List<GameObject> spawnablePrefabs;
    private string savePath => Application.persistentDataPath + "/dynamic_data.dat";


    private List<DynamicSaveCompAbs> dynamicObjects = new List<DynamicSaveCompAbs>();
    private List<object> dynamicSpawnData = new List<object>();

    private List<object> current = new List<object>();


    // 注册
    public void RegisterSaveable(DynamicSaveCompAbs obj)
    {
        dynamicObjects.Add(obj);
    }

    // 取消
    public void UnregisterSaveable(DynamicSaveCompAbs obj)
    {
        dynamicObjects.Remove(obj);
    }


    private void Start()
    {
        if (!File.Exists(savePath)) return;
        using (FileStream stream = new FileStream(savePath, FileMode.Open))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            current = (List<object>)formatter.Deserialize(stream);
            LoadSpawnedObjects();
        }
    }

    // 保存场景数据
    public void SaveScene()
    {
        // 存档前先clear一下 防止重复存档
        dynamicSpawnData.Clear();
        // 保存的 数据
        foreach (var obj in dynamicObjects)
        {
            if (obj == null)
            {
                Debug.Log("对象已被销毁");
            }
            else
            {
                DynamicSpawnData data = new DynamicSpawnData();
                data.prefabId = obj.prefabId;
                data.position = JsonUtility.ToJson(obj.transform.position);
                data.rotation = JsonUtility.ToJson(obj.transform.rotation);
                data.data = obj.SaveData();
                dynamicSpawnData.Add(JsonConvert.SerializeObject(data));
            }
        }

        using (FileStream stream = new FileStream(savePath, FileMode.Create))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, dynamicSpawnData);
        }
    }


    // 加载生成的对象
    public void LoadSpawnedObjects()
    {
        foreach (var item in current)
        {
            DynamicSpawnData data = JsonConvert.DeserializeObject<DynamicSpawnData>(item.ToString());
            GameObject instance = SpawnObject(data.prefabId,
                JsonUtility.FromJson<Vector3>(data.position),
                JsonUtility.FromJson<Quaternion>(data.rotation));
            if (instance != null && data.data != null)
            {
                instance.GetComponent<DynamicSaveCompAbs>()?.LoadData(data.data);
            }
        }
    }

    // 生成对象
    public GameObject SpawnObject(string prefabId, Vector3 pos, Quaternion rot)
    {
        GameObject prefab = spawnablePrefabs.Find(p => p.name == prefabId);
        if (prefab == null) return null;

        GameObject instance = Instantiate(prefab, pos, rot);
        return instance;
    }
}